// pages/hundredDetailed/hundredDetailed.js
const app = getApp()
const utils = require('../../utils/util.js')
var WxParse = require('../../wxParse/wxParse.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dirty: [],
    type: '',
    id: '',
    item: '',
    list: [],
    zflist: [],
    showzf: true,
    pageNumber: 1,
    userInfo: '',
    whetherSetPayPwd: false,
    walletBalance: null,
    focus: false,
    initiator: false,
    share2: false,
    share1: false,
    totalPages: 1,
    totalPages1: 1,
    phoneshow: false,
    loginShow: false,
    login: false,
    phone: false,
  },
  emit() {
    this.setData({
      pageNumber: 1,
      zflist: []
    })
    // console.log('领取完',this.data.pageNumber)
    this.getlist()
  },
  login() {
    if (this.data.login) {
      this.toggle('phoneshow', true)
      this.selectComponent('#phone').showClose()
    } else {
      this.toggle('loginShow', true)
      this.selectComponent('#login').showClose()
    }
  },
  toggleToast(e) {
    console.log(e.detail)
    if (!e.detail.loginShow) {
      this.toggle('loginShow', false)
    }
    this.onShow()
  },
  toggleToast1(e) {
    console.log(e.detail)
    if (!e.detail.phoneshow) {
      this.toggle('phoneshow', false)
    }
    this.onShow()
  },
  toggle(type, val) {
    this.setData({
      [type]: val
    });
  },
  //导出数据
  toExportList() {
    wx.navigateTo({
      url: "/pages/exportList/exportList?actId=" + this.data.id + '&type=' + this.data.type
    })
  },
  call(e) {
    var dataset = e.currentTarget.dataset;
    wx.makePhoneCall({
      phoneNumber: dataset.tel
    })
  },
  cancelact() {
    var that = this
    wx.showModal({
      content: '是否取消活动',
      confirmColor: '#2168EB',
      success(res) {
        if (res.confirm) {
          app.req({
            url: 'blessmini/birthAct/cancelAct',
            data: {
              actId: that.data.id,
              actType: parseInt(that.data.type)
            },
            method: 'POST',
            success: function (res) {
              if (res.code == 200) {
                wx.showToast({
                  title: '活动取消成功',
                  duration: 2000,
                })
                setTimeout(function () {
                  wx.switchTab({
                    url: '/pages/index/index'
                  })
                }, 2000)
              }
            }
          })
        } else if (res.cancel) {
        }
      }
    })
  },
  //图片点击预览
  previewImg: function (e) {
    // console.log(e.currentTarget.dataset.index);
    var index = e.currentTarget.dataset.index;
    var imgArr = this.data.item.pictureList;
    // console.log('图片地址', this.data.act2.posterUrl)
    // console.log(imgArr);
    wx.previewImage({
      current: imgArr[index],     //当前图片地址
      urls: imgArr,               //所有要预览的图片的地址集合 数组形式
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  cancelTrip() {
    var that = this
    console.log('点击')
    if (that.data.item.moneyWay == 2) {
      wx.showModal({
        content: '是否取消行程',
        confirmColor: '#2168EB',
        success(res) {
          if (res.confirm) {
            app.req({
              url: 'blessmini/enrol/cancelTrip',
              data: {
                actId: that.data.id,
                actType: parseInt(that.data.type)
              },
              method: 'POST',
              success: function (res) {
                if (res.code == 200) {
                  wx.showToast({
                    title: '行程取消成功',
                  })
                  wx.switchTab({
                    url: '/pages/index/index'
                  })
                }
              }
            })
          } else if (res.cancel) {
          }
        }
      })
    } else if (that.data.item.moneyWay == 1) {
      wx.showModal({
        title: '是否取消行程',
        content: '如需退还礼金，需自行联系活动发起人',
        confirmColor: '#2168EB',
        success(res) {
          if (res.confirm) {
            app.req({
              url: 'blessmini/enrol/cancelTrip',
              data: {
                actId: that.data.id,
                actType: parseInt(that.data.type)
              },
              method: 'POST',
              success: function (res) {
                if (res.code == 200) {
                  wx.showToast({
                    title: '行程取消成功',
                  })
                  wx.switchTab({
                    url: '/pages/index/index'
                  })
                }
              }
            })
          } else if (res.cancel) {
          }
        }
      })
    }
  },
  signBtn() {
    var that = this
    app.req({
      url: 'blessmini/enrol/sign',
      data: {
        blessActId: that.data.id,
        blessActType: parseInt(that.data.type)
      },
      method: 'POST',
      success: function (res) {
        if (res.code == 200) {
          wx.showToast({
            title: '签到成功',
          })
          that.getdetailed()
        }
      }
    })
  },
  tohome() {
    wx.switchTab({
      url: '/pages/index/index'
    })
  },
  getdetailed() {
    var that = this
    app.req({
      url: 'blessmini/blesscommon/birthdayDetails',
      data: {
        id: that.data.id,
        actType: parseInt(that.data.type)
      },
      method: 'POST',
      success: function (res) {
        if (res.code == 200) {
          // if (res.data.organizerId == that.data.userInfo.id){
          //   that.setData({
          //     initiator: true
          //   })
          //   console.log('发起人', that.data.initiator, res.data.organizerId, res.data.createUid, that.data.userInfo.id)
          // } else
          if (res.data.createUid == that.data.userInfo.id) {
            that.setData({
              initiator: true
            })
          } else {
            that.setData({
              initiator: false,
            })
            console.log('非发起人', that.data.initiator, res.data.organizerId, res.data.createUid, that.data.userInfo.id)
          }
          res.data.createTime = utils.itemDateToShow(res.data.createTime, 1, false, false).substring(5)
          res.data.startTime = utils.itemDateToShow(res.data.startTime, 1, true, false)
          if (res.data.type == 2) {
            wx.setNavigationBarTitle({
              title: '寿宴'
            })
          } else if (res.data.type == 3) {
            wx.setNavigationBarTitle({
              title: '百日宴'
            })
          }
          WxParse.wxParse('activityProcess', 'html', res.data.description, that, 5);
          that.setData({
            item: res.data,
            type: res.data.type
          })
          console.log('详情', that.data.item)
        }
      }
    })
  },
  // type：1返回修改，2重新提交；
  toUpdate() {
    if (this.data.type == 2) {
      wx.redirectTo({
        url: "/pages/birthdayParty/birthdayParty?actId=" + this.data.item.id + "&type=1"
      })
    } else if (this.data.type == 3) {
      wx.redirectTo({
        url: "/pages/hundredParty/hundredParty?actId=" + this.data.item.id + "&type=1"
      })
    }
  },
  getRegistrationInformation() {
    var that = this
    app.req({
      url: 'blessmini/enrol/getRegistrationUser',
      data: {
        actId: that.data.id,
        pageSize: 10,
        pageNumber: that.data.pageNumber
      },
      method: 'POST',
      success: function (res) {
        if (res.code == 200) {
          for (var item of res.data.blessEnrolList.rows) {
            item.createTime = utils.itemDateToShow(item.createTime, 1, false, false).substring(5)
          }
          if (that.data.pageNumber == 1) {
            that.setData({
              list: res.data.blessEnrolList.rows,
            })
          } else {
            that.setData({
              list: that.data.list.concat(res.data.blessEnrolList.rows),
            })
          }
          that.setData({
            totalPages1: res.data.blessEnrolList.totalPages
          })
        }
      }
    })
  },
  getlist() {
    var that = this
    app.req({
      url: "blessmini/blesscomment/blessingList",
      data: {
        actId: that.data.id,
        pageNumber: that.data.pageNumber,
        pageSize: 10
      },
      method: "post",
      success: function (res) {
        if (res.code == 200) {
          for (var item of res.data.page.rows) {
            item.createTime = item.createTime.substring(5, 16)
          }
          if (that.data.pageNumber == 1) {
            that.setData({
              zflist: res.data.page.rows,
            })
          } else {
            that.setData({
              zflist: that.data.zflist.concat(res.data.page.rows),
            })
          }
          that.setData({
            totalPages: res.data.page.totalPages
          })
          console.log('活动列表', that.data.list)
        }
      }
    })
  },
  showbtn(e) {
    var num = e.currentTarget.dataset.num
    if (num == 1) {
      this.setData({
        showzf: true,
        pageNumber: 1,
      })
    } else if (num == 2) {
      this.setData({
        showzf: false,
        pageNumber: 1,
      })
    }
  },
  topage() {
    var that = this;
    var my = 0
    if (that.data.type == 2) {
      var receiveId = that.data.item.organizerId
    } else if (that.data.type == 3) {
      var receiveId = that.data.item.createUid
    }
    if (this.data.item.organizerId == this.data.userInfo.id || this.data.item.createUid == that.data.userInfo.id) {
      my = 1
    }
    wx.navigateTo({
      url: '/pages/outRed/outRed?actId=' + this.data.item.id + "&receiveId=" + receiveId + "&actType=" + that.data.type + "&name=" + this.data.item.organizerName + '&my=' + my,
    })
  },
  //点击送祝福
  topLeaveMsg: function () {
    this.setData({
      focus: true
    })
  },
  //送祝福
  formName: function (e) {
    this.setData({
      inputname: e.detail.value.replace(/\s+/g, '')
    })
  },
  bindblur: function (e) {
    this.setData({
      // inputname: e.detail.value.replace(/\s+/g, ''),
      focus: false
    })
  },
  //确认  
  confirmreply: function (e) {
    var that = this
    console.log('发送', that.data.inputname)
    if (that.data.inputname == '') {
      wx.showToast({
        title: '内容不能为空',
        icon: 'none',
        duration: 2000
      })
    } else {
      if (that.data.inputname != '') {
        var n = 0
        // console.log('词库2', this.data.dirty.length)
        for (var i = 0; i < this.data.dirty.length; i++) {
          // console.log('循环')
          if (that.data.inputname.indexOf(this.data.dirty[i]) >= 0) {
            console.log('查询2')
            wx.showToast({
              title: '您输入的内容有违禁词，敏感词已被替换成星号,请编辑后重新提交',
              icon: 'none',
              duration: 2000
            })
            var fw = this.data.dirty[i]
            var fw1 = ''
            for (var k = 0; k < fw.length; k++) {
              fw1 = fw1 + '*'
            }
            var activityProcess = that.data.inputname.replace(fw, fw1)
            that.setData({
              inputname: activityProcess
            });
            console.log('替换', that.data.inputname)
            // console.log('替换1', activityProcess)
            n = n + 1
          }
        }
        if (n > 0) {
          return
        }
      }
      if (that.data.type == 2) {
        var receiveId = that.data.item.organizerId
      } else if (that.data.type == 3) {
        var receiveId = that.data.item.receiveId
      }
      console.log('接收者id', receiveId)
      app.req({
        url: "blessmini/blessword/save",
        method: "post",
        data: {
          blessActId: that.data.id,
          blessActType: that.data.type,
          content: that.data.inputname,
          receiveId: receiveId
        },
        success: function (res) {
          console.log(res)
          if (res.code == 200) {
            wx.showToast({
              title: '祝福成功',
              icon: 'none',
              duration: 2000
            })
            that.setData({
              inputname: ''
            })
            that.onShow()
          } else {
            wx.showToast({
              title: '发送失败',
              icon: 'none',
              duration: 2000
            })
          }
        }
      });
    }
    this.setData({
      focus: false
    })
  },
  showGPS: function () {
    var that = this;
    var data = that.data.item;
    const latitude = data.latitude * 1;
    const longitude = data.longitude * 1;
    const name = data.adress;
    const address = data.adress;
    var data = {
      latitude,
      longitude,
      scale: 18,
      name,
      address
    };
    var that = this;
    wx.openLocation(data);
  },
  //获取钱包余额
  getWalletBalance: function () {
    let that = this
    app.req({
      url: "blessmini/user/myBalance",
      method: "post",
      data: '',
      success: function (res) {
        console.log('获取钱包余额', res)
        if (200 == res.code) {
          that.setData({
            walletBalance: res.data.balance
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  //获取是否有密码
  getIspswd() {
    var that = this
    app.req({
      url: 'blessmini/user/whetherSetPayPwd',
      data: {
      },
      method: 'POST',
      success: function (res) {
        console.log('密码', res);
        if (res.code == 200) {
          that.setData({
            whetherSetPayPwd: res.data.whetherSetPayPwd
          })
        }
      }
    })
  },
  //跳转活动审核，报名信息
  toNextPage(e) {
    var that = this;
    var page = e.currentTarget.dataset.turn;
    wx.navigateTo({
      url: "/pages/activityState/activityState?actId=" + that.data.item.id + "&actType=" + that.data.type + "&type=" + page + '&createUid=' + that.data.item.createUid
    })
  },
  signup() {
    wx.navigateTo({
      url: '/pages/activityRegistration/activityRegistration?id=' + this.data.item.id + '&type=' + this.data.type,
    })
  },
  getdirty() {
    var that = this
    app.req({
      url: "/wechat/dirty/all",
      method: "post",
      success: function (res) {
        // console.log('脏字库')
        if (res.code == 200) {
          wx.setStorageSync('dirty', res.data);
          that.setData({
            dirty: res.data
          })
        }
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    that.setData({
      type: options.type,
      id: options.id
    })
    // that.getuserInfo()
    // that.setData({
    //   type: 2,
    //   id: "f5257935050e11ea945200163e05ff66"
    // })
    if (wx.getStorageSync('dirty') == undefined || wx.getStorageSync('dirty') == '') {
      this.getdirty()
    } else {
      this.setData({
        dirty: wx.getStorageSync('dirty')
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  getuserInfo() {
    var that = this
    if (wx.getStorageSync('uid') == '') {
      that.toggle("login", false);
    } else {
      that.toggle("login", true);
      if (wx.getStorageSync("phone") == '') {
        that.toggle("phone", true);
      } else {
        that.toggle("phone", false);
        that.toggle("phoneshow", false);
        that.toggle("loginShow", false);
        app.getUserInfo(function (userInfo) {
          that.toggle("userInfo", userInfo);
          that.getWalletBalance()
        })
      }
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    that.setData({
      pageNumber: 1,
      list: [],
      share2: false,
      share1: false,
    })
    console.log('刷新')
    that.getuserInfo()
    that.getdetailed()
    that.getRegistrationInformation()
    that.getlist()
    that.getIspswd()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this
    if (that.data.showzf) {
      if (that.data.totalPages > that.data.pageNumber) {
        that.setData({
          pageNumber: that.data.pageNumber + 1
        })
        that.getlist()
      }
    } else {
      if (that.data.totalPages1 > that.data.pageNumber) {
        that.setData({
          pageNumber: that.data.pageNumber + 1
        })
        that.getRegistrationInformation()
      }
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that = this
    var topic = ''
    if (that.data.item.createUid == that.data.userInfo.id) {
      that.setData({
        share2: true,
      })
    } else {
      that.setData({
        share1: true,
      })
    }
    if (that.data.type == 2) {
      topic = that.data.item.name
    } else if (that.data.type == 3) {
      topic = that.data.item.babyName
    }
    if (that.data.share1 || that.data.share2) {
      return {
        title: topic,
        path: '/pages/hundredDetailed/hundredDetailed?id=' + that.data.id + '&type=' + that.data.type,
      }
    }
  }
})